<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use Think\Model;
use User\Api\UserApi as UserApi;

class CaigouerController extends AdminController {
   public function index(){

      $sql="select batch,count(id) cnt,sum(status) status from gr_caigou_goods where status>1 and delflag=0 group by batch order by batch desc ";
      $model=new Model();
      $res=$model->query($sql);
      $total = count($res);
      if (isset($REQUEST['r'])) {
         $listRows = (int) $REQUEST['r'];
      } else {
         $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
      }
      $page = new \Think\Page($total, $listRows, $REQUEST);
      if ($total > $listRows) {
         $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
      }
      $p = $page->show();
      $this->assign('_page', $p ? $p : '');
      $this->assign('_total', $total);
      $sql.=" limit $page->firstRow,$page->listRows";
      $res=$model->query($sql);
      $this->assign('_list',$res);
      $this->display();
   }
   public function batchdetail($batch){
      $group_name=get_user_group_title(UID);
      $user_name=get_username(UID);
      $map['batch']=$batch;
      $map['status']=array('gt',1);
      $map['delflag']=0;
      $res=$this->lists('caigou_goods',$map,'createAt desc');
      $this->assign('_list',$res);
      $this->batch=$batch;
      $this->group_name=$group_name;
      $this->user_name=$user_name;
      $this->title="采购明细";
      $this->page=I('p');
      $this->display();
   }
   public function export($batch){
      $group_name=get_user_group_title(UID);
      $user_name=get_username(UID);
      if($group_name=="财务"||$user_name=='admin'){
         $headArray=array("商品名称", "规格", "总箱数", "总重", "每箱单价","每斤单价", "每箱箱费","单箱皮重","已存放时间", "产地", "备注", "创建时间");
         $sql = "select pname,spec,total_num,total_weight,unit_num_price,unit_weight_price,unit_box_fee,unit_box_weight,have_days,chandi,remark,DATE_FORMAT(from_unixtime(createAt),'%y-%m-%d %H:%i:%s') from gr_caigou_goods where batch='".$batch."' and delflag=0";
      }else{
         $headArray=array("商品名称", "规格", "总箱数", "总重", "每箱箱费","单箱皮重","已存放时间", "产地", "备注", "创建时间");
         $sql = "select pname,spec,total_num,total_weight,unit_box_fee,unit_box_weight,have_days,chandi,remark,DATE_FORMAT(from_unixtime(createAt),'%y-%m-%d %H:%i:%s') from gr_caigou_goods where batch='".$batch."' and delflag=0";
      }
      $Model = new Model();
      $data = $Model->query($sql);
      if ($data) {
         //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
         import("Org.Util.PHPExcel");
         import("Org.Util.PHPExcel.Writer.Excel5");
         import("Org.Util.PHPExcel.IOFactory.php");

         $filename = "output_order_excel";
         $headArr = $headArray;

         $title =$batch."采购列表";
         $this->getExcel($filename, $headArr, $data, $title);
      }else{
         $this->error("没有可导出的数据！");
      }
   }
   public function assoproduct($batch){
      $this->batch=$batch;
      $this->title="采购明细";
      $this->display();
   }
   public function predingjia(){
      $idArr=I('id');
      $pnameArr=I('pname');
      $specArr=I('spec');
      $batchArr=I('batch');
      $BINArr=I('BIN');
      $erpPnameArr=I('erp_pname');
      $erpSpecArr=I('erp_spec');
      $typeJsonArr=I('type_json');
      $totalNumArr=I('total_num');
      $unitNumPriceArr=I('unit_num_price');
      $totalWeightArr=I('total_weight');
      $unitWeightPriceArr=I('unit_weight_price');
      $unitBoxFeeArr=I('unit_box_fee');
      $unitBoxWeightArr=I('unit_box_weight');
      $lossArr=I('loss');
      $transFeeArr=I('trans_fee');
      $percentArr=I('percent');
      $costOffArr=I('cost_off');
      $valid=false;
      $valid=(array_vaild($idArr)===false)?$valid:true;
      $valid=(array_vaild($pnameArr)===false)?$valid:true;
      $valid=(array_vaild($specArr)===false)?$valid:true;
      $valid=(array_vaild($batchArr)===false)?$valid:true;
      $valid=(array_vaild($BINArr)===false)?$valid:true;
      $valid=(array_vaild($erpPnameArr)===false)?$valid:true;
      $valid=(array_vaild($erpSpecArr)===false)?$valid:true;
      $valid=(array_vaild($typeJsonArr)===false)?$valid:true;
      $valid=(array_vaild($totalNumArr)===false)?$valid:true;
      $valid=(array_vaild($unitNumPriceArr)===false)?$valid:true;
      $valid=(array_vaild($totalWeightArr)===false)?$valid:true;
      $valid=(array_vaild($unitWeightPriceArr)===false)?$valid:true;
      $valid=(array_vaild($unitBoxFeeArr)===false)?$valid:true;
      $valid=(array_vaild($unitBoxWeightArr)===false)?$valid:true;
      $valid=(array_vaild($lossArr)===false)?$valid:true;
      $valid=(array_vaild($transFeeArr)===false)?$valid:true;
      $valid=(array_vaild($percentArr)===false)?$valid:true;
      $valid=(array_vaild($costOffArr)===false)?$valid:true;
      if($valid===true){
         $this->error("数据不完整，请重新确认");
         return;
      }
      $model=M('Caigou_predingjia');
      $modelCaigouGoods=M('Caigou_goods');
      $model->startTrans();
      $modelCaigouGoods->startTrans();
      $commit=true;
      for($i=0;$i<count($idArr);$i++){
         $data=array(
            'id'=>$idArr[$i],
            'pname'=>$pnameArr[$i],
            'spec'=>$specArr[$i],
            'batch'=>$batchArr[$i],
            'BIN'=>$BINArr[$i],
            'erp_pname'=>$erpPnameArr[$i],
            'erp_spec'=>$erpSpecArr[$i],
            'type_json'=>$typeJsonArr[$i],
            'total_num'=>$totalNumArr[$i],
            'unit_num_price'=>$unitNumPriceArr[$i],
            'total_weight'=>$totalWeightArr[$i],
            'unit_weight_price'=>$unitWeightPriceArr[$i],
            'unit_box_fee'=>$unitBoxFeeArr[$i],
            'unit_box_weight'=>$unitBoxWeightArr[$i],
            'loss'=>$lossArr[$i],
            'trans_fee'=>$transFeeArr[$i],
            'percent'=>$percentArr[$i],
            'cost_off'=>$costOffArr[$i],
         );
         $res=$model->add($data,array(),true);
         $resCaigouGoods=$modelCaigouGoods->where(array('id'=>$idArr[$i]))->save(array('status'=>3));
         if(!$res&&$resCaigouGoods){
            $commit=false;
         }
      }
      if($commit){
         $model->commit();
         $modelCaigouGoods->commit();
         $this->success("数据保存成功");
      }else{
         $model->rollback();
         $modelCaigouGoods->rollback();
         $this->error("数据保存失败");
      }
   }
   public function predingjiaresult($batch){
      $map['batch']=$batch;
      $res=$this->lists('Caigou_predingjia',$map);
      $this->assign('_list',$res);
      $this->display();
   }
   private function getExcel($fileName, $headArr, $data, $title) {
      //对数据进行检验
      if (empty($data) || !is_array($data)) {
         //die("data must be a array");
      }
      //检查文件名
      if (empty($fileName)) {
         exit;
      }
      // H:i:s
      $date = date("Y_m_d_H_i_s", time());
      //$date = date("Y_m_d",time());
      $fileName .= "_{$date}.xls";

      //创建PHPExcel对象，注意，不能少了\
      $objPHPExcel = new \PHPExcel();
      $objProps = $objPHPExcel->getProperties();

      //第一列设置报表时间范围
      $key = ord("A");
      $colum = chr($key);
      $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $title);


      //第二列设置报表列头
      $key = ord("A");
      foreach ($headArr as $v) {
         $colum = chr($key);
         $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '2', $v);
         $key += 1;
      }

      $column = 3;
      $objActSheet = $objPHPExcel->getActiveSheet();
      foreach ($data as $key => $rows) { //行写入
         $span = ord("A");
         foreach ($rows as $keyName => $value) {// 列写入
            $j = chr($span);
            $objActSheet->setCellValue($j . $column, $value);
            $objActSheet->getColumnDimension('a')->setWidth(10);
            $objActSheet->getColumnDimension('b')->setWidth(10);
            $objActSheet->getColumnDimension('c')->setWidth(10);
            $objActSheet->getColumnDimension('d')->setWidth(10);
            $objActSheet->getColumnDimension('e')->setWidth(10);
            $objActSheet->getColumnDimension('f')->setWidth(10);
            $objActSheet->getColumnDimension('g')->setWidth(10);
            $objActSheet->getColumnDimension('h')->setWidth(10);
            $objActSheet->getColumnDimension('i')->setWidth(10);
            $objActSheet->getColumnDimension('j')->setWidth(10);
            $objActSheet->getColumnDimension('k')->setWidth(20);
            $span++;
         }
         $column++;
      }

      $fileName = iconv("utf-8", "gb2312", $fileName);
      //重命名表
      // $objPHPExcel->getActiveSheet()->setTitle('test');
      //设置活动单指数到第一个表,所以Excel打开这是第一个表
      $objPHPExcel->setActiveSheetIndex(0);
      header('Content-Type: application/vnd.ms-excel');
      header("Content-Disposition: attachment;filename=\"$fileName\"");
      header('Cache-Control: max-age=0');

      $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
      $objWriter->save('php://output'); //文件通过浏览器下载
      exit;
   }
   public function ajaxbindgood($pname,$spec){
      $l=mb_strlen($pname,'utf8');
      $sql="select * from gr_material_product where 1=1";
      for($i=1;$i<=$l;$i++){
         $sql.=" and pname like '%".substr($pname,$i)."%'";
      }

//      $sql="";
//      $res = M('material_product')->where($map)->select();
//      $this->assign('_list',$res);
//      $this->display();
   }
   public function ajaxGetCaigouListByBatch($batch){
      $map['batch']=$batch;
      $map['status']=array('gt',1);
      $map['delflag']=0;
      $res=M('caigou_goods')->where($map)->order('createAt desc')->select();
      $this->ajaxReturn($res);
   }
   public function ajaxGetPreDingjiaBatchList(){
      $model=M('caigou_predingjia');
      $res=$model->group('batch')->order('batch desc')->getField('batch',true);
      $this->ajaxReturn($res);
   }
   public function ajaxGetPreDingjiaBatchGoods($batch){
      $model=M('caigou_predingjia');
      $map['batch']=$batch;
      $res=$model->where($map)->select();
      $this->ajaxReturn($res);
   }

   /**
    * ajax快速保存处理结果
    * @param $data
    */
   public function ajaxPostQuickSave($data){
      $dataRes=json_decode($data,true);
      $model=M('Caigou_predingjia');
      if($model->add($dataRes,[],true)){
         $this->ajaxReturn(1);
      }else{
         $this->ajaxReturn(0);
      }
   }
}
